<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of soaUsers
 *
 * @author dxx
 */

namespace app\common\model\activity;
use app\common\model\oms\Brands as BrandsModel;

class CouponsBrands extends \think\Model {

    protected $table = 'coupons_brands';
    protected $connection = ['database' => 'activity'];

    /**
     * 构造方法
     * @param type $data
     */
    public function __construct($data=[]) {
        parent::__construct($data);
    }
    
    /**
     * 保存卡券和品牌的关系
     * @param type $couponsId  卡券 
     * @param type $brands 品牌的id数组
     */
    public function saveCouponsBrands($couponsId, $brands){
        //把此卡券相关的信息删除掉
        $res = $this->where(['coupons_id'=>$couponsId])->delete();
        if($res === false){
            return false;
        }
        
        $insertArr = [];
        foreach($brands as $brandId){
            $insertArr[] = ['coupons_id' => $couponsId, 'brand_id' => $brandId];
        }
        
        return $this->insertAll($insertArr);
    }
    
    
    
    /**
     * 根据优惠券ID获取适用品牌
     *
     * @return $couponsId
     */
    public function getBrandsByCouponsId($couponsId){
        
        $condition = [
            'coupons_id' => $couponsId,
        ];
        //获取品牌ID
        $info = $this->where($condition)->select();
        //根据品牌ID获取品牌详情
        if($info)
        {
            $brandsModel = new BrandsModel();
            foreach($info as $key=>$value){

                $data = $brandsModel->getOne(['brand_id'=>$value['brand_id']]);
                $info[$key]['brandname']=$data['brand_name'];
                $info[$key]['brandid']=$data['brand_id'];
                $info['brandList'][]=$data['brand_name'];
            }   
        }
        else
        {
            $info['brandList']=array();
        }
        $brands='';
        if($info['brandList'])
        {
            $brands=implode('、',$info['brandList']);
        }
        
        return $brands;
    }
    
    
    /**
     * 根据优惠券ID获取适用品牌(For 后台)
     * @return $couponsId
     */
    public function getBrandsListByCouponsId($couponsId){
        
        $info = $this->where(['coupons_id'=> $couponsId])->column('*');
        $brands = array_column($info, 'brand_id');
        $brandidList = implode(',',$brands); 

        return $brandidList;
    }
    
}